package com.xuecheng.order.api;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.xuecheng.base.exception.XueChengPlusException;
import com.xuecheng.order.config.AlipayConfig;
import com.xuecheng.order.model.dto.AddOrderDto;
import com.xuecheng.order.model.dto.PayRecordDto;
import com.xuecheng.order.model.dto.PayStatusDto;
import com.xuecheng.order.model.po.PayRecord;
import com.xuecheng.order.service.OrdersService;
import com.xuecheng.order.util.SecurityUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

@Api("订单相关接口")
@Slf4j
@RestController
public class OrderController {
    @Value("${pay.alipay.APP_ID}")
    public String appid;

    @Value("${pay.alipay.APP_PRIVATE_KEY}")
    public String appPrivateKey;

    @Value("${pay.alipay.ALIPAY_PUBLIC_KEY}")
    public String alipayPublicKey;

    @Autowired
    OrdersService ordersService;

    @ApiOperation("生成支付二维码接口")
    @PostMapping("/generatepaycode")
    public PayRecordDto generatePayCode(@RequestBody AddOrderDto addDto){
        SecurityUtil.XcUser user = SecurityUtil.getUser();
        if(user == null){
            XueChengPlusException.cast("请登录后再支付");
        }
        return ordersService.createOrder(addDto,user.getId());
    }

    @ApiOperation("扫码下单接口")
    @GetMapping("/requestpay")
    public void requestPay(Long payNo, HttpServletResponse response) throws IOException {
        PayRecord record = ordersService.getPayRecordByPayNo(payNo);
        if(record == null){
            XueChengPlusException.cast("当前支付记录不存在，请重新点击二维码");
        }
        if("601002".equals(record.getStatus())){
            XueChengPlusException.cast("订单已支付，请勿重复支付。");
        }
        //构造sdk的客户端对象，获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.URL,appid, appPrivateKey,
                AlipayConfig.FORMAT,AlipayConfig.CHARSET, alipayPublicKey,AlipayConfig.SIGNTYPE);
        //创建API对应的request
        AlipayTradeWapPayRequest alipayRequest = new AlipayTradeWapPayRequest();
        //设置支付后回跳和通知地址
//        alipayRequest.setReturnUrl("http://domain.com/CallBack/return_url.jsp");
        alipayRequest.setNotifyUrl("http://edbc5a28.natappfree.cc/orders/receivenotify");
        //填充业务参数
        alipayRequest.setBizContent("{" +
                " \"out_trade_no\":\"" + record.getPayNo() + "\"," +
                " \"total_amount\":\"" + record.getTotalPrice() + "\"," +
                " \"subject\":\"" + record.getOrderName() + "\"," +
                " \"product_code\":\"QUICK_WAP_PAY\"" +
                " }");
        String form = "";
        try{
            //请求支付宝下单接口，发送http请求，调用sdk生成表单
            form = alipayClient.pageExecute(alipayRequest).getBody();
        }catch(AlipayApiException e){
            e.printStackTrace();
        }
        response.setContentType("text/html;charset=" + AlipayConfig.CHARSET);
        //直接将完整的表单html输出到页面
        response.getWriter().write(form);
        response.getWriter().flush();
        response.getWriter().close();
    }

    @ApiOperation("查询支付结果")
    @GetMapping("/payresult")
    public PayRecordDto payResult(Long payNo){
        return ordersService.queryPayResult(payNo);
    }

    @ApiOperation("接收支付结果通知")
    @PostMapping("/receivenotify")
    public void receiveNotify(HttpServletRequest request,HttpServletResponse out)
            throws AlipayApiException, UnsupportedEncodingException {
        Map<String,String> params = new HashMap<>();
        Map requestParams = request.getParameterMap();
        for(Iterator iter = requestParams.keySet().iterator();iter.hasNext();){
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for(int i=0;i<values.length;i++){
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            params.put(name,valueStr);
        }
        //验签
        boolean verify_result = AlipaySignature.rsaCheckV1(params,alipayPublicKey,
                AlipayConfig.CHARSET,"RSA2");
        if(verify_result){
            //验证成功
            //商户订单号
            String out_trade_no = new String(request.getParameter("out_trade_no")
                    .getBytes("ISO-8859-1"),"UTF-8");
            //支付宝交易号
            String trade_no = new String(request.getParameter("trade_no")
                    .getBytes("ISO-8859-1"),"UTF-8");
            //交易状态
            String trade_status = new String(request.getParameter("trade_status")
                    .getBytes("ISO-8859-1"),"UTF-8");
            //appid
            String app_id = new String(request.getParameter("app_id")
                    .getBytes("ISO-8859-1"),"UTF-8");
            //total_amount
            String total_amount = new String(request.getParameter("total_amount")
                    .getBytes("ISO-8859-1"),"UTF-8");
            //支付成功的处理逻辑
            if(trade_status.equals("TRADE_SUCCESS")){
                PayStatusDto dto = new PayStatusDto();
                dto.setOut_trade_no(out_trade_no);
                dto.setTrade_status(trade_status);
                dto.setApp_id(app_id);
                dto.setTrade_no(trade_no);
                dto.setTotal_amount(total_amount);
                //保存成功的支付结果
                ordersService.saveAliPayStatus(dto);
            }
        }
    }
}
